package com.self.educenter.controller;

import com.google.gson.Gson;
import com.self.commonutils.JwtUtils;
import com.self.educenter.entity.UcenterMember;
import com.self.educenter.service.UcenterMemberService;
import com.self.educenter.utils.ConstantPropertiesUtils;
import com.self.educenter.utils.HttpClientUtils;
import com.self.servicebase.handler.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;


    //2.获取扫描人信息，添加数据
    //扫码之后通过通过域名进行跳转到这个方法，然后重定向到3000端口
    @GetMapping("callback")
    public String callback(String code ,String state){
        try{
            //在这可以获取扫码人的信息,需要按照流程走
            System.out.println("code:" + code);
            System.out.println("state:" + state);

            //1.获取code值，临时票据，是一个随机唯一值

            //2.拿着code请求微信固定的地址，得到access_token和openid
            //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三个参数：id，密钥 和code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantPropertiesUtils.WX_OPEN_APP_ID,
                    ConstantPropertiesUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //请求这个拼接好的地址，得到返回的两个值：access_token和openid
            //使用HTTPClient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo:" + accessTokenInfo);

            //从accessTokenInfo字符串中获取出来两个值：access_token和openid
            //将accessTokenInfo字符串转换map集合，根据map里面的key获取对应的值
            //使用JSON转换工具GSON
            Gson gson = new Gson();
            HashMap accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) accessTokenMap.get("access_token");
            String openid = (String) accessTokenMap.get("openid");

            //3.通过access_token和openid,再去请求微信提供固定的地址，获取到扫描人信息*/
            /*String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(
                    baseUserInfoUrl,
                    access_token,
                    openid
            );
            //使用HTTPClient发送请求，获取数据
            String userInfo = HttpClientUtils.get(userInfoUrl);
            System.out.println("userInfo:" + userInfo);

            //获取userInfo中的扫描人信息
            HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
            String  nickname = (String) userInfoMap.get("nickname");//昵称
            String headimgurl = (String) userInfoMap.get("headimgurl");//头像*/

            //扫码人信息添加进数据库里面
            //判断数据库表里存不存在相同微信信息，根据openid判断
            UcenterMember member = memberService.getMemberByOpenId(openid);
            if(member == null){ //如果member为空，表示表中没有数据，进行添加

                // 3.通过access_token和openid,再去请求微信提供固定的地址，获取到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                //使用HTTPClient发送请求，获取数据
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo:" + userInfo);

                //获取userInfo中的扫描人信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String  nickname = (String) userInfoMap.get("nickname");//昵称
                String headimgurl = (String) userInfoMap.get("headimgurl");//头像

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                member.setGmtCreate(new Date());
                member.setGmtModified(new Date());
                memberService.save(member);
            }

            //使用jwt根据member对象生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            //返回首页面,通过路径传递token字符串
            return "redirect:http://localhost:3000?token=" + token;

        }catch(Exception e){
            e.printStackTrace();
            throw new MyException(20001,"登录失败");
        }


    }


/*
    //获取扫码人信息，添加数据
    @GetMapping("callback")
    public String callback(String code,String state){

        System.out.println(code);
        System.out.println(state);

        try{
            //1.获取code值，临时票据，类似于验证码

            //2.根据code请求微信固定地址，获取access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            //给三个参数设置值
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantPropertiesUtils.WX_OPEN_APP_ID,
                    ConstantPropertiesUtils.WX_OPEN_APP_SECRET,
                    code);

            //请求accessTokenUrl,获取access_token和openId
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);//请求地址，所以是get请求
            System.out.println("accessToken= " + accessTokenInfo);

            //获取的是JSON字符串，解析JSON转化成Map结构
            Gson gson = new Gson();
            HashMap map = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken =  (String) map.get("access_token");
            String openid = (String) map.get("openid");


            //将扫码人信息加入数据库
            //判断数据库中是否已经有了相同数据，根据openid查询
            UcenterMember member =  memberService.getMemberByOpenId(openid);
            System.out.println(member);
            if(member == null){

                //根据access_token和openid再去请求微信固定地址，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);

                //httpClients请求数据，获取用户信息
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo = " + userInfo);

                //用户信息的map集合
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");//昵称
                String headImgUrl = (String) userInfoMap.get("headimgurl");//头像
                System.out.println(nickname);
                System.out.println(headImgUrl);

                //将扫码人信息加入数据库
                 member = new UcenterMember();
                 member.setOpenid(openid);
                 member.setNickname(nickname);
                 member.setAvatar(headImgUrl);
                 System.out.println("需要保存的用户：" + member);
                 memberService.save(member);
                System.out.println("保存之后的用户信息：" + member);
            }

            //使用JWT根据member对象生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            System.out.println("token = " + token);

            //最后：回到首页面，通过路径传递token字符串
            return "redirect:http://localhost:3000?token=" + token;
        }catch(Exception e){
           throw new MyException(20001,"登录失败~~");
        }

    }*/


    //1. 生成微信扫描二维码
    @GetMapping("login")
    public String getWxCode(){

        //固定地址，后面拼接参数
//        String url = "https://open.weixin.qq.com/" +
//                "connect/qrconnect?appid="+ ConstantWxUtils.WX_OPEN_APP_ID+"&response_type=code";

        // 微信开放平台授权baseUrl  %s相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantPropertiesUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        }catch(Exception e) {
            e.printStackTrace();
        }

        //设置%s里面值
        String url = String.format(
                baseUrl,
                ConstantPropertiesUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "xiaozeng"
        );

        //重定向到请求微信地址里面
        return "redirect:"+url;

    }
}
